//
//  CZNewFeatureViewController.swift
//  微博08
//
//  Created by apple on 16/2/29.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let ItemCount = 4

class CZNewFeatureViewController: UICollectionViewController {
    // MARK: - 属性
    var layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    // 实现没有参数的构造函数
    init() {
        // layout不能懒加载
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1.注册cell
        self.collectionView!.registerClass(CZNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        // 设置布局
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        collectionView?.bounces = false
        collectionView?.pagingEnabled = true
    }
}

// MARK: - CollectionView相关
extension CZNewFeatureViewController {
    // 返回cell数量
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return ItemCount
    }
    
    // 返回cell内容
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 直接去缓存池中查找,如果查找不到会使用注册的cell的类型来创建cell并返回
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CZNewFeatureCell
        
        cell.itemIndex = indexPath.item
        
        // 在这个地方做动画不合适,这里是cell即将显示就调用了.
//        cell.scaleAnimation()
        
        return cell
    }
    
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 获取当前显示的是哪一页
        // scrollView实际上是collectionView
        let index = Int(scrollView.contentOffset.x / scrollView.bounds.size.width)
        
        // 判断是否是最后一页
        if index == ItemCount - 1 {
            // 获取cell,在调用cell的动画
            let visibleIndexPath = NSIndexPath(forItem: index, inSection: 0)
            if let cell = collectionView?.cellForItemAtIndexPath(visibleIndexPath) as? CZNewFeatureCell {
                cell.scaleAnimation()
            }
        }
    }
}

// 自定义的cell
class CZNewFeatureCell: UICollectionViewCell {
    
    // MARK: - 属性
    var itemIndex: Int = 0 {
        didSet {
            // 当控制器给itemIndex赋值后,我们根据itemIndex来设置对应的图片
            bkgImageView.image = UIImage(named: "new_feature_\(itemIndex + 1)")
            startButton.hidden = true
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 准备UI
    private func prepareUI() {
        // 1.添加子控件
        // cell需要把子控件添加到contentView
        contentView.addSubview(bkgImageView)
        contentView.addSubview(startButton)
        
        // 2.添加约束
//        bkgImageView.translatesAutoresizingMaskIntoConstraints = false
//        startButton.translatesAutoresizingMaskIntoConstraints = false
        
        // bkgImageView填充contentView
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bkgView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkgView" : bkgImageView]))
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[bkgView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkgView" : bkgImageView]))
        
        bkgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        
        // 开始体验按钮
        // CenterX和父控件CenterX重合
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
//        
//        // Bottom和父控件的Bottom间距-160
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
        
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-160)
        }
    }
    
    private func scaleAnimation() {
        // 显示按钮
        startButton.hidden = false
        
        // 先设置transform scale = 0
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        UIView.animateWithDuration(1, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            // 改变transform
//            startButton.transform = CGAffineTransformMakeScale(1, 1)
            // 还原默认的transform
            self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                print("动画完成")
        }
    }
    
    // MARK: - 按钮点击事件
    func startButtonClick() {
        // 跳转到MainViewController
//        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
//        appDelegate.switchRootViewController(true)
        AppDelegate.outSwitchRootViewController(true)
    }
    
    // MARK: - 懒加载
    // 背景
    lazy var bkgImageView: UIImageView = UIImageView(image: UIImage(named: "new_feature_1"))
    
    // 开始体验按钮
    lazy var startButton: UIButton = {
        let button = UIButton()
        
        // 设置
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.setTitle("开始体验", forState: UIControlState.Normal)
        
        button.sizeToFit()
        
        button.addTarget(self, action: "startButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
}
